package com.zy.ems.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zy.ems.common.base.BaseController;
import com.zy.ems.common.exception.ApiException;
import com.zy.ems.common.exception.BaseErrorStatus;
import com.zy.ems.common.exception.BusinessException;
import com.zy.ems.common.util.GetParameterUtil;
import com.zy.ems.common.util.ResultTool;
import com.zy.ems.common.util.StringUtils;
import com.zy.ems.model.MemberEntity;
import com.zy.ems.service.MemberService;
import com.zy.ems.utils.exceptions.MemberCode;

@RestController
@RequestMapping("/member")
public class MemberController extends BaseController {

	@Autowired
	private MemberService memberService;

	@RequestMapping(value = "login.json", method = RequestMethod.POST)
	public Object login(HttpServletRequest request) {
		String userName = StringUtils.parseStr(request.getParameter("userName"));
		String password = StringUtils.parseStr(request.getParameter("password"));

		if (StringUtils.isEmpty(userName, password)) {
			return ResultTool.error(BaseErrorStatus.sys_008);
		}

		try {
			MemberEntity memberEntity = memberService.login(userName, password);

			if (memberEntity == null) {
				return ResultTool.error(MemberCode.mem_1001);
			}

			return ResultTool.success(memberEntity);
		} catch (ApiException e) {
			return ResultTool.error(e);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultTool.error(e);
		}
	}

	@RequestMapping(value = "register.json", method = RequestMethod.POST)
	public Object register(HttpServletRequest request) {

		try {
			GetParameterUtil util = new GetParameterUtil();
			StringBuilder para = new StringBuilder();
			para.append("userName").append(",password").append(",mobile").append(",email");

			Map<String, String> param = util.getPara(request, para.toString());
			if (StringUtils.isEmpty(param.get("userName"), param.get("password"))) {
				return ResultTool.error(MemberCode.mem_1002);
			}

			if (StringUtils.isEmpty(param.get("mobile"), param.get("email"))) {
				return ResultTool.error(MemberCode.mem_1003);
			}

			boolean result = this.memberService.register(param);

			if (result) {
				return ResultTool.success();
			} else {
				return ResultTool.error(MemberCode.sys_007.addMsg("注册失败."));
			}

		} catch (BusinessException e) {
			return ResultTool.error(e);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultTool.error(e);
		}
	}
}
